package com.zang.hash;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author ZVerify
 * @since 2022/10/14 11:32
 * @see <a href="https://leetcode.cn/problems/3sum/">...</a>
 **/
public class 三数之和 {

    /**
     * @param nums 整数数组
     * @return {@link List}<{@link List}<{@link Integer}>> 所有和为 0 且不重复的三元组。
     */
    public List<List<Integer>> threeSum(int[] nums) {

        ArrayList<List<Integer>> list = new ArrayList<>();

        Arrays.sort(nums);

        for (int i = 0;i<nums.length;i++){

            if (nums[i] > 0) continue;
            if (i>0 && nums[i] == nums[i-1]) continue;

            int left = i+1;
            int right = nums.length-1;
            while (left < right ){
                int sum = nums[i] + nums[left] + nums[right];
                if (sum > 0){
                    right--;
                } else if (sum<0) {
                    left++;
                }else {
                    list.add(Arrays.asList(nums[i], nums[left], nums[right]));

                    while (left < right && nums[right] == nums[right - 1]) right--;
                    while (left < right && nums[left] == nums[left + 1]) left++;

                    right--;
                    left++;
                }
            }
        }
        return list;
    }

}
